1272E - Nearest Opposite Parity - CodeForces Solution


dfs and similar graphs shortest paths *1900

Please click on ads to support us..

C++ Code:

#include<bits/stdc++.h>
using namespace std;

const int N=2e5+10;

int T,n,m;
int a[N];
int dist[N];
queue<int> q;
vector<int> sons[N];

void solve()
{
    memset(dist,0x3f,sizeof(dist));

    cin>>n;
    for(int i=1;i<=n;i++) cin>>a[i];

    for(int i=1;i<=n;i++)
    {
        int t=i-a[i];
        if(t>=1)
        {
            if(a[i]%2==a[t]%2) sons[t].push_back(i);
            else dist[i]=1;
        }

        t=i+a[i];
        if(t<=n)
        {
            if(a[t]%2==a[i]%2) sons[t].push_back(i);
            else dist[i]=1;
        }
    }

    for(int i=1;i<=n;i++)
    {
        if(dist[i]==1) q.push(i);
    }

    while(!q.empty())
    {
        int u=q.front();
        q.pop();

        for(int i=0;i<sons[u].size();i++)
        {
            int k=sons[u][i];
            if(dist[k]>dist[u]+1)
            {
                dist[k]=dist[u]+1;
                q.push(k);
            }
        }
    }

    for(int i=1;i<=n;i++)
    {
        if(dist[i]!=0x3f3f3f3f) cout<<dist[i]<<' ';
        else cout<<"-1 ";
    }
}

signed main()
{
    ios::sync_with_stdio(false);
    cin.tie(0),cout.tie(0);

    //cin>>T;
    T=1;
    
    while(T--) 
        solve();
    
    return 0;
}


Comments

Submit
0 Comments
More Questions

1569C - Jury Meeting
108A - Palindromic Times
46A - Ball Game
114A - Cifera
776A - A Serial Killer
25B - Phone numbers
1633C - Kill the Monster
1611A - Make Even
1030B - Vasya and Cornfield
1631A - Min Max Swap
1296B - Food Buying
133A - HQ9+
1650D - Twist the Permutation
1209A - Paint the Numbers
1234A - Equalize Prices Again
1613A - Long Comparison
1624B - Make AP
660B - Seating On Bus
405A - Gravity Flip
499B - Lecture
709A - Juicer
1358C - Celex Update
1466B - Last minute enhancements
450B - Jzzhu and Sequences
1582C - Grandma Capa Knits a Scarf
492A - Vanya and Cubes
217A - Ice Skating
270A - Fancy Fence
181A - Series of Crimes
1638A - Reverse